<template>
	<view class="container">
		<view class="main-content">
			<view class="hit u-flex u-flex-between u-flex-items-center u-padding-right-20">
				<view class="section-title u-flex ">
					<view class="u-margin-right-15">
						<u-image src="@/static/index/car.png" width="20" height="20"></u-image>
					</view>
					<view class="">订单详情</view>
				</view>
				<view style="color: #67c93c;">{{ taskDetail.processStatus || '待排班' }}</view>
			</view>

			<view class="detail-section">
				<scroll-view class="detail-content" scroll-y>
					<div v-if="taskDetails.length">
						<view class="detail-item" style="font-weight: 600;">货物明细</view>
						<view class="u-margin-bottom-45" v-for="(item,index) in getGoodsTableValue(taskDetail.goodsTable)" :key="index">
							<view class="detail-item " v-for="detail in taskDetailGoodInfo" :key="detail.label">
								<label>{{ detail.label }}</label>
								<text>
									{{detail.key=='quantity' ?parseFloat(item[detail.key]): item[detail.key] }}
								</text>
							</view>
						</view>
						<view class="detail-item" style="font-weight: 600;">基本信息</view>
						<view class="detail-item" v-for="detail in taskDetails" :key="detail.label">
							<label>{{ detail.label }}</label>
							<text>{{ taskDetail[detail.key] || '无' }}</text>
						</view>
						<view v-if="taskDetail.processStatus!='待排班'">
							<view class="detail-item" v-if="taskDetail.processStatus!='待装车'">
								<label>装车时间</label>
								<text>{{ formatDateTime(taskDetail.actualLoadingTime) }}</text>
							</view>
							<view class="detail-item" v-if="taskDetail.processStatus!='待装车' && taskDetail.processStatus!='待发货'">
								<label>发货时间</label>
								<text>{{ formatDateTime(taskDetail.actualdepartureTime) }}</text>
							</view>
							<view class="detail-image" v-if="zcImageData.length">
								<image class="image" :src="item.fileContent" v-for="(item,index) in zcImageData" mode="aspectFit"
									@click="previewImage2(index, 'zc')"></image>
							</view>
							<view class="detail-item" v-if="taskDetail.processStatus=='已完成'|| taskDetail.processStatus=='待审核'">
								<label>送达时间</label>
								<text>{{ formatDateTime(taskDetail.actualdepartureTime)}}</text>
							</view>
							<view class="detail-image" v-if="sdImageData.length">
								<image class="image" :src="item.fileContent" v-for="(item,index) in sdImageData" mode="aspectFit"
									@click="previewImage2(index, 'sd')"></image>
							</view>
						</view>
					</div>
					<view v-else class="no-selection">
						<text>请选择任务查看详情</text>
					</view>
				</scroll-view>

				<button class="btn-dispatch" @click="openDispatchModal" v-if="taskDetail.processStatus=='待排班' && job!='107'">
					派单
				</button>
				<button class="btn-audit" @click="openConfirmModal" v-if="taskDetail.processStatus=='待装车' && job=='107'">
					确认装车
				</button>
				<button class="btn-audit" @click="openConfirmModal" v-if="taskDetail.processStatus=='待发货' && job=='107'">
					确认发货
				</button>
				<button class="btn-audit" @click="openConfirmModal" v-if="taskDetail.processStatus=='待送达' && job=='107'">
					确认送达
				</button>
				<button class="btn-audit" @click="openAuditModal" v-if="taskDetail.processStatus=='待审核' && job!='107'">
					审核
				</button>
			</view>
		</view>
		<!-- 授权状态提示 -->
		<view class="auth-status" v-if="authStatus">
			<text :class="['status-text', authStatus.type]">
				{{ authStatus.message }}
			</text>
		</view>

		<!-- 派单弹窗 -->
		<u-popup :show="showDispatchModal" mode="center" :round="15" @close="closeDispatchModal" closeOnClickOverlay :z-index="998"
			safeAreaInsetBottom>
			<view class="dispatch-popup">
				<view class="popup-header">
					<text class="popup-title">选择派单信息</text>
					<u-icon name="close" color="#999" size="20" @click="closeDispatchModal"></u-icon>
				</view>

				<view class="popup-content">
					<!-- 方式选择 -->
					<view class="form-item">
						<text class="form-label">派送方式</text>
						<view class="picker-wrapper">
							<u-radio-group v-model="delivery">
								<u-radio label="物流公司" name="物流公司"></u-radio>
								<u-radio label="司机" name="司机"></u-radio>
								<u-radio label="无需发货" name="无需发货"></u-radio>
							</u-radio-group>
						</view>
					</view>
					<!-- 物流公司选择 -->
					<view class="form-item" v-if="delivery=='物流公司'">
						<text class="form-label">物流公司</text>
						<view class="picker-wrapper" @click="showCompanyPicker = true">
							<text class="picker-value" :class="{placeholder: !selectedCompany.name}">
								{{ selectedCompany.name || '请选择物流公司' }}
							</text>
							<u-icon name="arrow-down" color="#c8c9cc" size="14"></u-icon>
						</view>
					</view>

					<!-- 司机选择 -->
					<view class="form-item" v-if="delivery=='司机'">
						<text class="form-label">司机</text>
						<view class="picker-wrapper" @click="showDriverPicker = true" :class="{disabled: !selectedCompany.id}">
							<text class="picker-value" :class="{placeholder: !selectedDriver.name}">
								{{ selectedDriver.name || '请选择司机' }}
							</text>
							<u-icon name="arrow-down" color="#c8c9cc" size="14"></u-icon>
						</view>
						<!-- <text v-if="!selectedCompany.id" class="tip-text">请先选择物流公司</text> -->
					</view>
				</view>

				<view class="popup-footer">
					<button class="btn-cancel" @click="closeDispatchModal">取消</button>
					<button class="btn-confirm" open-type="subscribeMessage" :subscribe-message-template-id-list="templateIdList" subscribe-message-scene="enterPage" @click="handleDispatchConfirm">确认派单</button>
				</view>
			</view>
		</u-popup>

		<!-- 确认弹窗 -->
		<u-popup :show="showConfirmModal" mode="center" :round="15" @close="closeConfirmModal" closeOnClickOverlay :z-index="998"
			safeAreaInsetBottom>
			<view class="dispatch-popup">
				<view class="popup-header">
					<text class="popup-title" v-if="taskDetail.processStatus">确认{{taskDetail.processStatus.slice(1,3)}}</text>
					<u-icon name="close" color="#999" size="20" @click="closeConfirmModal"></u-icon>
				</view>

				<view class="popup-content">
					<!-- 费用区域 -->
					<view class="form-section" v-if="taskDetail.processStatus=='待送达'">
						<view class="form-row">
							<view class="form-item">
								<text class="form-label">里程：</text>
								<u-input v-model="confirmForm.mileage" placeholder="请输入里程" type="number" border="none"
									inputAlign="right" class="form-input">
									<template #suffix>
										<text class="unit">公里</text>
									</template>
								</u-input>
							</view>

							<view class="form-item">
								<text class="form-label">单价：</text>
								<u-input v-model="confirmForm.unitPrice" placeholder="请输入单价" type="digit" border="none"
									inputAlign="right" class="form-input">
									<template #suffix>
										<text class="unit">元</text>
									</template>
								</u-input>
							</view>
						</view>

						<view class="form-row">
							<view class="form-item">
								<text class="form-label">体积：</text>
								<u-input v-model="confirmForm.volume" placeholder="请输入体积" type="number" border="none" inputAlign="right"
									class="form-input">
									<template #suffix>
										<text class="unit">m³</text>
									</template>
								</u-input>
							</view>

							<view class="form-item">
								<text class="form-label">重量：</text>
								<u-input v-model="confirmForm.weight" placeholder="请输入重量" type="number" border="none" inputAlign="right"
									class="form-input">
									<template #suffix>
										<text class="unit">吨</text>
									</template>
								</u-input>
							</view>
						</view>

						<view class="form-item full-width">
							<text class="form-label">其他费用：</text>
							<u-input v-model="confirmForm.otherExpenses" placeholder="请输入其他费用" type="digit" border="none"
								inputAlign="right" class="form-input">
								<template #suffix>
									<text class="unit">元</text>
								</template>
							</u-input>
						</view>
					</view>
					<!-- 拍摄上传区域 -->
					<view class="upload-section">
						<text class="upload-title">拍摄上传:</text>
						<view class="upload-area">
							<!-- 已上传的图片预览 -->
							<view v-if="uploadedImages.length" class="images-preview">
								<view v-for="(image, index) in uploadedImages" :key="index" class="image-preview-item">
									<image :src="image.url" class="preview-image" mode="aspectFit" @click="previewImage(index)"></image>
									<view class="image-actions">
										<view class="delete-btn" @click="removeImage(index)">
											<u-icon name="close" color="#fff" size="16"></u-icon>
										</view>
									</view>
								</view>
								
								<!-- 继续上传按钮 -->
								<view v-if="uploadedImages.length < 6" class="upload-btn continue-upload" @click="chooseImage">
									<u-icon name="plus" size="30" color="#ccc"></u-icon>
									<text class="upload-text">继续添加</text>
									<text class="upload-count">{{ uploadedImages.length }}/6</text>
								</view>
							</view>

							<!-- 未上传时的上传按钮 -->
							<view v-else class="upload-btn" @click="chooseImage">
								<u-icon name="camera" size="40" color="#ccc"></u-icon>
								<text class="upload-text">点击上传图片(最多6张)</text>
							</view>
						</view>
					</view>
				</view>

				<view class="popup-footer">
					<button class="btn-cancel" @click="closeConfirmModal">取消</button>
					<button class="btn-confirm" open-type="subscribeMessage" :subscribe-message-template-id-list="templateIdList" subscribe-message-scene="enterPage" @click="handleConfirmLoad">确认</button>
				</view>
			</view>
		</u-popup>

		<!-- 审核弹窗 -->
		<u-popup :show="showAuditModal" mode="center" :round="15" @close="closeAuditModal" closeOnClickOverlay :z-index="998"
			safeAreaInsetBottom>
			<view class="audit-popup">
				<view class="popup-header">
					<text class="popup-title">是否审核通过</text>
					<u-icon name="close" color="#999" size="20" @click="closeAuditModal"></u-icon>
				</view>

				<view class="audit-content">
					<!-- 订单详细信息 -->
					<view class="audit-info-section">
						<view class="info-grid">
							<view class="info-item">
								<text class="info-label">里程：</text>
								<text class="info-value">{{ taskDetail.mileage || '0' }} 公里</text>
							</view>
							<view class="info-item">
								<text class="info-label">单价：</text>
								<text class="info-value">¥{{ taskDetail.unitPrice || '0' }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">体积：</text>
								<text class="info-value">{{ taskDetail.volume || '0' }} 立方米</text>
							</view>
							<view class="info-item">
								<text class="info-label">重量：</text>
								<text class="info-value">{{ taskDetail.weight || '0' }} 吨</text>
							</view>
							<view class="info-item">
								<text class="info-label">其他费用：</text>
								<text class="info-value">¥{{ auditInfo.otherExpenses || '0' }}</text>
							</view>
						</view>
					</view>

					<!-- 物流信息 -->
					<!--         <view class="audit-info-section">
            <view class="info-title">物流信息</view>
            <view class="info-simple">
              <view class="info-item">
                <text class="info-label">物流公司：</text>
                <text class="info-value">{{ auditInfo.logisticsCompany || '无' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">司机：</text>
                <text class="info-value">{{ auditInfo.driver || '无' }}</text>
              </view>
            </view>
          </view> -->

					<!-- 审核备注 -->
					<!-- <view class="form-item">
            <text class="form-label">审核备注</text>
            <u-textarea
              v-model="auditNotes"
              placeholder="请输入审核备注（可选）"
              maxlength="200"
              :autoHeight="true"
            ></u-textarea>
          </view> -->

					<!-- 审核结果选择 -->
					<!--    <view class="audit-radio-group">
            <text class="radio-label">审核结果：</text>
            <view class="radio-buttons">
              <view 
                :class="['radio-button', auditResult === 'pass' ? 'active' : '']"
                @click="auditResult = 'pass'"
              >
                <u-icon :name="auditResult === 'pass' ? 'checkbox-mark' : ''" color="#fff" size="14"></u-icon>
                <text>审核通过</text>
              </view>
              <view 
                :class="['radio-button', auditResult === 'reject' ? 'active reject' : 'reject']"
                @click="auditResult = 'reject'"
              >
                <u-icon :name="auditResult === 'reject' ? 'checkbox-mark' : ''" color="#fff" size="14"></u-icon>
                <text>审核不通过</text>
              </view>
            </view>
          </view>
      -->
				</view>

				<view class="popup-footer">
					<button class="btn-cancel" @click="closeAuditModal">取消</button>
					<button class="btn-confirm" open-type="subscribeMessage" :subscribe-message-template-id-list="templateIdList" subscribe-message-scene="enterPage" @click="handleAuditConfirm">确认审核</button>
				</view>
			</view>
		</u-popup>

		<!-- 物流公司选择器 -->
		<u-picker :show="showCompanyPicker" :columns="[logisticsCompanies]" keyName="gender" title="选择物流公司"
			@cancel="showCompanyPicker = false" @confirm="onCompanyConfirm" :closeOnClickOverlay="true"></u-picker>

		<!-- 司机选择器 -->
		<u-picker :show="showDriverPicker" :columns="[allDrivers]" keyName="name" title="选择司机"
			@cancel="showDriverPicker = false" @confirm="onDriverConfirm" :closeOnClickOverlay="true"
			:disabled="!selectedCompany.id"></u-picker>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		reactive,
		onMounted,
		onUnmounted,
		watch,
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		userApi,
		logisticsApi
	} from '@/api/index.js'
	import {
		useUser
	} from '@/composables/useUser'
	import imageToBase64 from '@/utils/imageToBase64';
	import {
		getCurrentDateTime
	} from '@/utils/dateFormat'
	import { useSubscribeMessage } from '@/composables/useSubscribeMessage'
	const {
		job,
		username,
		userId
	} = useUser()

	// 响应式数据
	const showDispatchModal = ref(false);
	const showConfirmModal = ref(false);
	const showAuditModal = ref(false);
	const showCompanyPicker = ref(false);
	const showDriverPicker = ref(false);

	const uploadedImages = ref([])
	const imageFile = ref(null)
	const isLoading = ref(false)

	const delivery = ref('物流公司');
	
	// 使用订阅消息 Hook
	const templateIdList = ['8BYCmgqMs93PA1OxJao3t5VxI-6XxBiR_jKuUVHqIWQ','Ujvb0IIzDKOrXOpn6x4GK8-95F7fDKTikONYnbUxaNc','ExFc4_BMBkSpEGNgLtaji2tXBjWwSpoPbkUki99hbgE']
	
	const {
	    hasSubscribed,
	    isLoading: isSubscribing,
	    authStatus,
	    showReAuthTip,
	    triggerSubscribe,
	    checkSubscriptionStatus
	} = useSubscribeMessage(templateIdList, {
	    forceSubscribe: true, // 强制订阅
	    autoCheckStatus: true // 自动检查状态
	})
	

	const radiolist1 = reactive([{
			name: '物流公司',
		},
		{
			name: '司机',
		},
		{
			name: '无需发货',
		},

	]);

	// 表单数据
	const selectedCompany = reactive({
		id: null,
		name: ''
	});
	const selectedDriver = reactive({
		id: null,
		name: '',
		phone:''
	});

	// 响应式数据 - 确认表单
	const confirmForm = reactive({
		mileage: '',
		unitPrice: '',
		volume: '',
		weight: '',
		otherExpenses: ''
	});

	const auditNotes = ref('');
	const auditResult = ref('pass'); // pass: 通过, reject: 不通过


	// 审核信息
	const auditInfo = reactive({
		distance: '150',
		unitPrice: '1000',
		volume: '100',
		weight: '100',
		otherFees: '100',
		totalAmount: '150000',
		logisticsCompany: '顺丰速运',
		driver: '张师傅'
	});

	// 模拟数据
	const logisticsCompanies = ref([])

	const allDrivers = ref([]);
	//图片数据
	const imageData = ref([]);

	const taskDetails = ref([{
			label: 'ID：',
			key: 'id'
		},
		{
			label: '客户名称：',
			key: 'customerName',
		},
		{
			label: '收货联系人：',
			key: 'receiverContact'
		},
		{
			label: '收货联系电话：',
			key: 'receiverPhone'
		},
		{
			label: '客户地址：',
			key: 'customerAddress'
		},
		{
			label: '归属公司：',
			key: 'belongCompany'
		},
		{
			label: '货物明细：',
			key: 'custItem',
			type: 'goodsTable'
		},
		{
			label: '物流公司：',
			key: 'logisticsNo'
		},
		{
			label: '司机：',
			key: 'transporterName'
		},
		{
			label: '司机联系方式：',
			key: 'transporterPhone'
		}
	]);
	
	const taskDetailGoodInfo = ref([{
			label: '货物名称：',
			key: 'goodsName',
		},
		{
			label: '客户料号：',
			key: 'remarks',
		},
		// {
		// 	label: '规格：',
		// 	key: 'spec',
		// 	type: 'goodsTable'
		// },
		{
			label: '数量：',
			key: 'quantity',
		}
		// {
		// 	label: '描述：',
		// 	key: 'description'
		// }
	]);

	const taskDetail = ref({})


	const isFormValid = computed(() => {
		return selectedCompany.id || selectedDriver.id;
	});

	//非送达图片
	const zcImageData = computed(() => {
		return imageData.value.filter(item => item.imgType == 'ZCZP');
	});

	//送达图片
	const sdImageData = computed(() => {
		return imageData.value.filter(item => item.imgType == 'SDZP');
	});



	// 打开派单弹窗
	const openDispatchModal = () => {
		showDispatchModal.value = true;
	};

	const closeDispatchModal = () => {
		showDispatchModal.value = false;
		// 重置表单
		selectedCompany.id = null;
		selectedCompany.name = '';
		selectedDriver.id = null;
		selectedDriver.name = '';
		selectedDriver.phone = '';
		showCompanyPicker.value = false;
		showDriverPicker.value = false;
	};

	// 打开确认弹窗
	const openConfirmModal = () => {
		showConfirmModal.value = true;
	};

	const closeConfirmModal = () => {
		showConfirmModal.value = false
		// 重置表单数据
		Object.assign(confirmForm, {
			mileage: '',
			unitPrice: '',
			volume: '',
			weight: '',
			otherExpenses: '0'
		});
	};


	const getImageData = async () => {
		let dataValue = taskDetail.value.processStatus == '待送达' ? 'SDZP' : 'ZCZP'
		let params = {
			mainId: taskDetail.value.id,
			imgType: dataValue
		}
		const res = await logisticsApi.getImageData(taskDetail.value.id, params);
		imageData.value = res.data
	}

	const chooseImage = async () => {
		try {
			const remainingCount = 6 - uploadedImages.value.length;
			if (remainingCount <= 0) {
				uni.showToast({
					title: '最多只能上传6张图片',
					icon: 'none'
				});
				return;
			}
			const res = await uni.chooseImage({
				count: remainingCount,
				sizeType: ['compressed'],
				sourceType: ['camera', 'album'],
				success: (res) => {
					if (res.tempFilePaths.length > 0) {
						// 将新选择的图片添加到数组中
						const newImages = res.tempFilePaths.map((path, index) => ({
							url: path,
							file: res.tempFiles[index],
							uploading: false,
							success: false,
							error: false
						}));
						uploadedImages.value = [...uploadedImages.value, ...newImages];
					}
				}
			})
		} catch (error) {
			console.error('选择图片失败:', error)
			uni.showToast({
				title: '选择图片失败',
				icon: 'none'
			})
		}
	}
	
	// 删除图片
	const removeImage = (index) => {
		uploadedImages.value.splice(index, 1);
	};

	// 预览图片
	const previewImage = (index) => {
		if (uploadedImages.value.length > 0) {
			const urls = uploadedImages.value.map(img => img.url);
			uni.previewImage({
				urls: urls,
				current: index
			});
		}
	};

	// 预览图片
	const previewImage2 = (index, type) => {
		let arr = []
		if (type == 'zc') arr = zcImageData.value
		if (type == 'sd') arr = sdImageData.value
		if (arr.length) {
			arr = arr.map(item => item.fileContent)
			console.log(arr, index);
			uni.previewImage({
				urls: arr,
				current: index
			})
		}
	}

	// 确认装车
	const handleConfirmLoad = async () => {
		let nextLabel = taskDetail.value.processStatus == '待装车' ? '待发货' : taskDetail.value.processStatus == '待发货' ?
			'待送达' : '待审核'
		let nextValue = taskDetail.value.processStatus == '待装车' ? 'sending' : taskDetail.value.processStatus == '待发货' ?
			'delivering' : 'reviewing'
		if (uploadedImages.value.length === 0) {
			uni.showToast({
				title: '请至少上传一张图片',
				icon: 'none'
			});
			return;
		}
		authStatus.value = null
		try {
			// 第一步：进行订阅消息授权[1](@ref)
			const subscribeResult = await triggerSubscribe()
			
			if(subscribeResult){
				uni.showLoading({
					title: '处理中...'
				});
				
				uploadedImages.value = uploadedImages.value.map(img => ({
					...img,
					uploading: true,
					success: false,
					error: false
				}));

				
				// 批量上传图片
				const uploadPromises = uploadedImages.value.map(async (image, index) => {
					try {
						// 使用封装的imageToBase64方法
						const base64Data = await imageToBase64(image.url, {
							quality: 1, // 可以适当降低质量以减少文件大小
						});
	
						const fileContent = base64Data.split(',')[1];
	
						const uploadParams = {
							addId: userId.value,
							addName: username.value,
							fileContent: fileContent,
							fileName: `${taskDetail.value.processStatus == '待送达' ? 'delivery' : 'loading'}_${Date.now()}_${index}.jpg`,
							imgType: taskDetail.value.processStatus == '待送达' ? 'SDZP' : 'ZCZP',
							mainId: taskDetail.value.id
						};
	
						const result = await logisticsApi.addImageBase64(uploadParams);
						
						// 更新图片状态为成功
						uploadedImages.value[index] = {
							...uploadedImages.value[index],
							uploading: false,
							success: true,
							error: false
						};
						
						return result;
					} catch (error) {
						// 更新图片状态为失败
						uploadedImages.value[index] = {
							...uploadedImages.value[index],
							uploading: false,
							success: false,
							error: true
						};
						throw error;
					}
				});
	
				// 等待所有图片上传完成
				await Promise.all(uploadPromises);
				
				// 检查是否有上传失败的图片
				const failedUploads = uploadedImages.value.filter(img => img.error);
				if (failedUploads.length > 0) {
					uni.showToast({
						title: `${failedUploads.length}张图片上传失败`,
						icon: 'none'
					});
					// 可以选择继续处理或停止
				}
				
				let params = {
					processStatus: nextLabel,
					id: taskDetail.value.id,
					updateId: userId.value,
					updateUser: username.value,
				}
				if (taskDetail.value.processStatus == '待装车') params['actualLoadingTime'] = getCurrentDateTime()
				if (taskDetail.value.processStatus == '待发货') params['actualdepartureTime'] = getCurrentDateTime()
				if (taskDetail.value.processStatus == '待送达') {
					params = Object.assign(params, confirmForm)
					params['arrivalTime'] = getCurrentDateTime()
				}
				console.log(params);
				const res = await logisticsApi.putDeliveryPlan(params);

				uni.hideLoading();
				refreshPreData(nextLabel, nextValue)
			}else {
            // 授权失败，阻止登录
            authStatus.value = {
                type: 'error',
                message: '请授权订阅消息以继续使用'
            }
        }
		} catch (error) {
			console.error('处理失败:', error);
			uni.showToast({
				title: error.message || '处理失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};
	const getUserDataFun = async () => {
		try {
			let bol = delivery.value == '物流公司'
			const res = await userApi.getUserlist({
				deptId: bol ? 39 : 38
			})
			if (bol) logisticsCompanies.value = res.data
			else allDrivers.value = res.data
		} catch (error) {
			console.error('获取失败:', error)
		}
	}

	// 审核弹窗相关方法
	const openAuditModal = () => {
		// 从任务详情中获取审核信息
		if (taskDetail.value) {
			// 这里可以根据实际数据结构进行调整
			Object.assign(auditInfo, {
				distance: taskDetail.value.distance || '',
				unitPrice: taskDetail.value.unitPrice || '',
				volume: taskDetail.value.volume || '',
				weight: taskDetail.value.weight || '',
				otherFees: taskDetail.value.otherFees || '',
				totalAmount: taskDetail.value.totalAmount || '',
				logisticsCompany: taskDetail.value.logisticsCompany || '',
				driver: taskDetail.value.driverName || ''
			});
		}
		showAuditModal.value = true;
	};

	const closeAuditModal = () => {
		showAuditModal.value = false;
		// 重置审核表单
		auditNotes.value = '';
		auditResult.value = 'pass';
	};

	const handleAuditConfirm = async () => {
		try {
			
			// 第一步：进行订阅消息授权[1](@ref)
			const subscribeResult = await triggerSubscribe()
			
			if(subscribeResult){
				uni.showLoading({
					title: '审核中...'
				});

				// 修改状态
				let params = {
					processStatus: '已完成',
					id: taskDetail.value.id,
					updateId: userId.value,
					updateUser: username.value,
				}

				const res = await logisticsApi.putDeliveryPlan(params);


				if (res.code == 200) {
					closeAuditModal();
					uni.hideLoading();
					uni.showToast({
						title: `审核通过`,
						icon: 'success'
					});
					refreshPreData('已完成', 'completed')
				}
			}else{
				// 授权失败，阻止登录
				authStatus.value = {
				    type: 'error',
				    message: '请授权订阅消息以继续使用'
				}
			}
		} catch (error) {
			console.error('审核失败:', error);
			uni.showToast({
				title: '审核失败，请重试',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};

	const onCompanyConfirm = (e) => {
		const company = e.value[0];
		selectedCompany.id = company.id;
		selectedCompany.name = company.gender;
		selectedCompany.phone = company.phoneNumber;
		console.log(selectedCompany);
		// 选择新公司时清空已选司机
		selectedDriver.id = null;
		selectedDriver.name = '';
		showCompanyPicker.value = false;
	};

	const onDriverConfirm = (e) => {
		const driver = e.value[0];
		selectedDriver.id = driver.id;
		selectedDriver.name = driver.name;
		selectedDriver.phone = driver.phoneNumber;
		showDriverPicker.value = false;
	};

	const handleDispatchConfirm = async () => {
		console.log(selectedCompany.id, selectedDriver.id);
		if (!isFormValid.value) {
			uni.showToast({
				title: '请先选择物流公司或者司机',
				icon: 'none'
			});
			return;
		}
		
		authStatus.value = null

		try {
			// 第一步：进行订阅消息授权[1](@ref)
			const subscribeResult = await triggerSubscribe()
			
			if(subscribeResult){
				uni.showLoading({
					title: '派单中...'
				});
				let params = {
					processStatus: '待发货',
					id: taskDetail.value.id,
					updateId: userId.value,
					updateUser: username.value,
					transporterId: delivery.value == '物流公司' ? selectedCompany.id : delivery.value == '司机' ? selectedDriver.id :
						'',
					transporterName:delivery.value == '物流公司' ? selectedCompany.name : delivery.value == '司机' ? selectedDriver.name :
						'',
					transporterPhone:delivery.value == '物流公司' ? selectedCompany.phone : delivery.value == '司机' ? selectedDriver.phone :
						'',
				}
				const res = await logisticsApi.putDeliveryPlan(params);
				if (res.code == 200) {
					// 派单成功
					uni.showToast({
						title: '派单成功',
						icon: 'success'
					});
				
					console.log('派单信息:', {
						物流公司: selectedCompany.name,
						司机: selectedDriver.name,
						派单时间: new Date().toLocaleString()
					});
				
					closeDispatchModal();
					refreshPreData('待发货', 'sending')
				
				
				}
			}else{
				
			}
			
		} catch (error) {
			console.error('派单失败:', error);
			uni.showToast({
				title: '派单失败，请重试',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};
	const refreshPreData = (status, loadingType) => {
		// 获取页面栈和上一页实例 [1,3,4](@ref)
		const pages = getCurrentPages();
		const prevPage = pages[pages.length - 2]; // 获取上一页页面实例

		setTimeout(() => {
			uni.navigateBack({
				delta: 1,
				success: () => {
					uni.$emit('refreshOrderList', {
						status,
						loadingType
					});
				}
			});
		}, 1000);
	}
	// 安全的JSON解析
	const getGoodsTableValue = (goodsTable) => {
		if (!goodsTable) return []

		try {
			// 如果已经是数组，直接使用
			if (Array.isArray(goodsTable)) {
				return goodsTable || []
			}

			// 如果是字符串，尝试解析
			if (typeof goodsTable === 'string') {
				// 检查是否是有效的JSON字符串
				if (goodsTable.trim().startsWith('[') || goodsTable.trim().startsWith('{')) {
					const parsed = JSON.parse(goodsTable)
					if (Array.isArray(parsed) && parsed.length > 0) {
						return parsed|| []
					}
				}
			}

			return '无'
		} catch (error) {
			console.warn('解析货物表格数据失败:', error)
			return '无'
		}
	}

	// 安全的时间格式化
	const formatDateTime = (dateTimeString) => {
		if (!dateTimeString) return '无'

		// 处理可能的字符串'null'或'undefined'
		if (dateTimeString === 'null' || dateTimeString === 'undefined') {
			return '无'
		}

		try {
			if (typeof dateTimeString === 'string') {
				return dateTimeString.replace('T', ' ').replace('Z', '')
			}
			return String(dateTimeString)
		} catch (error) {
			return '无'
		}
	}

	watch([showDispatchModal, delivery], (newval) => {
		console.log('newval', newval);
		if (newval[1] != '无需发货' && newval[0]) getUserDataFun()
	})

	// 生命周期
	onLoad(() => {
		
		// 获取当前页面栈
		const pages = getCurrentPages();
		// 当前页面实例是页面栈的最后一个
		const currentPage = pages[pages.length - 1];
		// 从当前页面实例上获取事件通道
		const eventChannel = currentPage.getOpenerEventChannel();

		eventChannel.on('acceptTaskData', (data) => {
			console.log(data);
			taskDetail.value = data.task;
			if (['待送达', '待发货', '待审核', '已完成'].includes(taskDetail.value.processStatus)) {
				getImageData()
			}
		});

	});
</script>

<style lang="scss" scoped>
	/* 原有样式保持不变 */
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.main-content {
		display: flex;
		flex: 1;
		padding: 20rpx;
		gap: 20rpx;
	}

	.detail-section {
		background-color: #ffffff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		display: flex;
		flex-direction: column;
		flex: 1.2;
	}

	.hit {
		background: #f2f8ff;
	}

	.section-title {
		padding: 24rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		border-bottom: 1px solid #f0f0f0;
	}

	.detail-content {
		flex: 1;
		margin: 30rpx 0rpx;
		max-height: 81vh;
		overflow-y: auto;
	}

	.detail-item {
		display: flex;
		margin-bottom: 20rpx;
		line-height: 1.6;
		padding: 0 50rpx;
	}

	.detail-image {
		position: relative;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
		width: 100%;
		padding: 20rpx;
		box-sizing: border-box;
		z-index: 1;

		.image {
			width: 100%;
			height: 200rpx;
			border-radius: 12rpx;
			object-fit: cover;
			background-color: #f5f5f5;
			transition: transform 0.3s ease;

			&:active {
				transform: scale(0.95);
			}
		}
	}

	.detail-item label {
		width: 200rpx;
		font-size: 26rpx;
		color: #666;
		flex-shrink: 0;
	}

	.detail-item text {
		flex: 1;
		font-size: 26rpx;
		color: #333;
		word-break: break-all;
	}

	.btn-dispatch,
	.btn-audit {
		margin: 20rpx 10rpx 30rpx 10rpx;
		background-color: #007AFF;
		color: white;
		padding: 10rpx;
		border-radius: 8rpx;
		border: none;
		font-size: 28rpx;
	}

	.btn-audit {
		background-color: #007AFF;
	}

	.btn-dispatch:disabled,
	.btn-audit:disabled {
		background-color: #ccc;
		cursor: not-allowed;
	}

	.no-selection {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200rpx;
		color: #999;
		font-size: 28rpx;
	}

	/* 审核弹窗样式 */
	.audit-popup,
	.dispatch-popup {
		width: 700rpx;
		background: #fff;
		border-radius: 15rpx;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.audit-content {
		padding: 40rpx 30rpx;
		max-height: 70vh;
		overflow-y: auto;
	}

	.audit-info-section {
		margin-bottom: 40rpx;
	}

	.info-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		padding-bottom: 10rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.info-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 20rpx;
	}

	.info-simple {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}

	.info-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 0;
	}

	.info-label {
		font-size: 26rpx;
		color: #666;
	}

	.info-value {
		font-size: 26rpx;
		color: #333;
		font-weight: 500;
	}

	.total-amount {
		color: #FF6B35;
		font-weight: bold;
		font-size: 28rpx;
	}

	.audit-radio-group {
		margin: 30rpx 0;
	}

	.radio-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}

	.radio-buttons {
		display: flex;
		gap: 20rpx;
	}

	.radio-button {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 8rpx;
		background: #f8f8f8;
		color: #666;
		font-size: 26rpx;
		transition: all 0.3s;
	}

	.radio-button.active {
		background: #007AFF;
		color: #fff;
		border-color: #007AFF;
	}

	.radio-button.reject.active {
		background: #FF6B35;
		border-color: #FF6B35;
	}

	.radio-button text {
		margin-left: 10rpx;
	}

	/* 弹窗通用样式 */
	.popup-content {
		padding: 30rpx 20rpx;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 40rpx 30rpx 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 40rpx;
	}

	.form-label {
		display: block;
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		width: 120rpx;
		text-align: right;
		padding-right: 10rpx;
		flex-shrink: 0;
	}

	.picker-wrapper {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 20rpx;
		border: 1rpx solid #e5e5e5;
		border-radius: 12rpx;
		background: #fafafa;
		flex: 1;
	}

	.popup-footer {
		display: flex;
		padding: 0 30rpx 40rpx;
		gap: 20rpx;
	}

	.btn-cancel,
	.btn-confirm {
		flex: 1;
		height: 75rpx;
		border-radius: 12rpx;
		font-size: 28rpx;
		border: none;
	}

	.btn-cancel {
		background: #f8f8f8;
		color: #333;
		border: 1rpx solid #e5e5e5;
	}

	.btn-confirm {
		background: #007AFF;
		color: white;
	}

	.upload-section {
		margin-bottom: 40rpx;
	}

	.upload-title {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 20rpx;
		display: block;
		font-weight: 500;
	}

	/* 修改上传区域样式以支持多图 */
	.upload-area {
		width: 100%;
	}
	
	.images-preview {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 20rpx;
	}
	
	.image-preview-item {
		position: relative;
		width: 100%;
		height: 200rpx;
		border-radius: 10rpx;
		overflow: hidden;
	}
	
	.preview-image {
		width: 100%;
		height: 100%;
		background: #f5f5f5;
	}
	
	.image-actions {
		position: absolute;
		top: 8rpx;
		right: 8rpx;
		z-index: 99999;
	}
	
	.delete-btn {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background: red;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.upload-btn {
		width: 100%;
		height: 200rpx;
		border: 2rpx dashed #ccc;
		border-radius: 10rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: #fafafa;
		gap: 10rpx;
		
		&.continue-upload {
			height: 200rpx;
		}
	}
	
	.upload-text {
		font-size: 24rpx;
		color: #999;
	}
	
	.upload-count {
		font-size: 20rpx;
		color: #ccc;
	}
	
	/* 上传状态指示器 */
	.upload-status {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.7);
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		gap: 10rpx;
		color: white;
		font-size: 20rpx;
	}
	
	/* 响应式调整 */
	@media (max-width: 768px) {
		.images-preview {
			grid-template-columns: repeat(2, 1fr);
		}
	}
	/* 响应式设计 */
	@media (max-width: 768px) {
		.main-content {
			flex-direction: column;
		}
	
		.detail-section {
			width: 100%;
		}
	
		.info-grid {
			grid-template-columns: 1fr;
		}
	}
</style>